//
//  BoardData.m
//  Maciago
//
//  Created by mmarcos on Wed Oct 03 2001.
//  Copyright (c) 2001 __CompanyName__. All rights reserved.
//

#import "BoardData.h"


@implementation BoardData

- init
{
    return [self initWithSize:kDefaultBoardSize];
}

- (id)initWithSize:(int)newSize
{
    size = newSize;
    data = calloc (sizeof(char), size*size);
    [self clear];
    return self;
}

- (id)initWithSize:(int)newSize data:(char *)newData
{
    size = newSize;
    data = calloc (sizeof(char), size*size);
    memcpy (data, newData, size*size);
    return self;
}

- (char)getValueAtX:(int)x y:(int)y
{
    if ((x < size) && (y < size))
	return data[size*x + y];
    return -1;
}

- (int)getSize
{
    return size;
}

- (BOOL)setValue:(char)value atX:(int)x y:(int)y
{
    if ((x < size) && (y < size))
    {
	data[size*x + y] = value;
	return YES;
    }
    return NO;
}

- (void)clear
{
    int i;
    for (i = 0; i < size*size; ++i)
        data[i] = kEmpty;
}

- (int)numberOfBlacks
{
    int i, nBlacks = 0;
    for (i = 0; i < size*size; ++i)
    {
        if ((data[i] & kBlackPiece) && !(data[i] & kLegalMove))
            ++nBlacks;
    }
    return nBlacks;
}

- (int)numberOfWhites
{
    int i, nWhites = 0;
    for (i = 0; i < size*size; ++i)
    {
        if ((data[i] & kWhitePiece)  && !(data[i] & kLegalMove))
            ++nWhites;
    }
    return nWhites;
}

- (void)auxDataX:(int *)outX y:(int *)outY
{
    *outX = auxX;
    *outY = auxY;
}

- (void)setAuxDataX:(int)inX y:(int)inY
{
    auxX = inX;
    auxY = inY;
}

- (void)dealloc
{
    free(data);
    [super dealloc];
}

- copy;
{
//    BoardData *bd;
//    int x, y;
    
    return [[BoardData alloc] initWithSize:size data:data];
    /*for (y = 0; y < size; ++y)
	for (x = 0; x < size; ++x)
	    [bd setValue:data[size*x + y] atX:x y:y];
    
    return bd;*/
}

- (struct board_data *)board_data
{
    int x, y;
    struct board_data *bd = board_data_create (size);
    
    //bd->size = size;
    
    for (x = 0; x < size; ++x)
    {
        for (y = 0; y < size; ++y)
        {
            bd->cell[x][y] = data[size*x + y];
        }
    }
    
    return bd;
}

- (void)set_board_data: (struct board_data *)bd
{
    int x, y;
    
    size = bd->size;
    
    for (x = 0; x < size; ++x)
    {
        for (y = 0; y < size; ++y)
        {
            data[size*x + y] = bd->cell[x][y];
        }
    }
}

@end
